<template>
  <div class="production-table-container h-full flex flex-col">
    <!-- 表格头部 -->
    <div class="table-header border-b border-#0efcff/30">
      <div class="table-row-padding table-row">
        <div class="table-grid">
          <div class="col-factory font-bold">厂区</div>
          <div class="col-workshop font-bold">车间</div>
          <div class="col-pool font-bold">水池编号</div>
          <div class="col-species font-bold">饲养品种</div>
        </div>
      </div>
    </div>

    <!-- 表格内容 -->
    <div class="table-body flex-1 overflow-hidden">
      <div
        class="table-content"
        :class="{ 'page-transition': isTransitioning }"
      >
        <div
          v-for="(item, index) in currentPageData"
          :key="`${currentPage}-${index}`"
          class="table-row-padding table-row border-b border-#0efcff/10 transition-colors hover:bg-#0efcff/5"
          :class="{ 'bg-#0efcff/3': index % 2 === 0 }"
        >
          <div class="table-grid">
            <div class="col-factory truncate">{{ item.factory }}</div>
            <div class="col-workshop">{{ item.workshop }}</div>
            <div class="col-pool text-#e0f836 font-bold">
              {{ item.poolNumber }}
            </div>
            <div class="col-species text-#66ccff font-bold">
              {{ item.species }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from "vue";
import { type ProductionItem, getBuildingData } from "../data/productionData";

interface Props {
  buildingId: number;
}

const props = defineProps<Props>();

const currentPage = ref(0);
const pageSize = ref(8); // 动态计算的每页显示数据
const isTransitioning = ref(false);
const rowHeight = ref(52); // 动态计算的每行高度（包括padding和border）
const containerHeight = ref(0);
const visibleRows = ref(0);
let pageTimer: ReturnType<typeof setInterval>;
let resizeTimer: ReturnType<typeof setTimeout>;

const productionData = ref<ProductionItem[]>([]);

// 动态字体大小
const dynamicFontSize = computed(() => {
  if (containerHeight.value < 300) {
    return "10px";
  } else if (containerHeight.value < 400) {
    return "11px";
  } else if (containerHeight.value > 800) {
    return "14px";
  } else {
    // 根据容器高度线性插值字体大小
    const ratio = (containerHeight.value - 400) / (800 - 400);
    const fontSize = 11 + (14 - 11) * ratio;
    return Math.round(fontSize) + "px";
  }
});

// 动态内边距
const dynamicPadding = computed(() => {
  if (containerHeight.value < 300) {
    return "0.5rem 1rem";
  } else if (containerHeight.value < 400) {
    return "0.75rem 1rem";
  } else {
    return "0.75rem 1rem";
  }
});

// 计算动态行高和可见行数
const calculateVisibleRows = () => {
  const container = document.querySelector(".table-body");
  if (container) {
    containerHeight.value = container.clientHeight;

    // 根据容器高度动态计算行高
    // 基础行高：最小40px，最大60px
    const minRowHeight = 40;
    const maxRowHeight = 60;

    // 根据容器高度调整行高
    if (containerHeight.value < 300) {
      // 极小屏幕：使用更小的行高
      rowHeight.value = 35;
    } else if (containerHeight.value < 400) {
      // 小屏幕：使用较小的行高
      rowHeight.value = minRowHeight;
    } else if (containerHeight.value > 800) {
      // 大屏幕：使用较大的行高
      rowHeight.value = maxRowHeight;
    } else {
      // 中等屏幕：根据容器高度线性插值
      const ratio = (containerHeight.value - 400) / (800 - 400);
      rowHeight.value = Math.round(
        minRowHeight + (maxRowHeight - minRowHeight) * ratio
      );
    }

    visibleRows.value = Math.floor(containerHeight.value / rowHeight.value);
    // 更新 pageSize，确保至少显示 3 行，最多显示计算出的可见行数
    pageSize.value = Math.max(3, Math.min(visibleRows.value, 15));
  }
};

// 当前页数据
const currentPageData = computed(() => {
  const start = currentPage.value * pageSize.value;
  const end = start + pageSize.value;
  return productionData.value.slice(start, end);
});

// 总页数
const totalPages = computed(() => {
  return Math.ceil(productionData.value.length / pageSize.value);
});

// 自动翻页
const startAutoPage = () => {
  if (pageTimer) {
    clearInterval(pageTimer);
  }

  pageTimer = setInterval(() => {
    if (totalPages.value > 1) {
      // 添加过渡效果
      isTransitioning.value = true;

      setTimeout(() => {
        currentPage.value = (currentPage.value + 1) % totalPages.value;
        isTransitioning.value = false;
      }, 150); // 150ms 过渡时间
    }
  }, 3000); // 每3秒翻页
};

// 监听楼栋变化
watch(
  () => props.buildingId,
  (newBuildingId) => {
    productionData.value = getBuildingData(newBuildingId);
    currentPage.value = 0;
    // 延迟计算可见行数，确保DOM已更新
    setTimeout(() => {
      calculateVisibleRows();
      startAutoPage();
    }, 100);
  },
  { immediate: true }
);

// 防抖的resize处理函数
const debouncedResize = () => {
  clearTimeout(resizeTimer);
  resizeTimer = setTimeout(() => {
    calculateVisibleRows();
    // 重新启动自动翻页以适应新的页面大小
    startAutoPage();
  }, 150);
};

onMounted(() => {
  // 延迟计算，确保DOM已渲染
  setTimeout(() => {
    calculateVisibleRows();
    startAutoPage();
  }, 100);

  // 监听窗口大小变化，使用防抖优化性能
  window.addEventListener("resize", debouncedResize);
});

onUnmounted(() => {
  if (pageTimer) {
    clearInterval(pageTimer);
  }
  if (resizeTimer) {
    clearTimeout(resizeTimer);
  }
  // 移除事件监听器
  window.removeEventListener("resize", debouncedResize);
});
</script>

<style scoped>
.production-table-container {
  font-size: v-bind("dynamicFontSize");
  color: #0efcff;
  transition: font-size 0.3s ease;
}

.table-row {
  min-height: v-bind('rowHeight + "px"');
  display: flex;
  align-items: center;
  transition: min-height 0.3s ease;
}

.table-row-padding {
  padding: v-bind("dynamicPadding");
  transition: padding 0.3s ease;
}

.table-header {
  background: rgba(14, 252, 255, 0.15);
  backdrop-filter: blur(5px);
  border-radius: 4px 4px 0 0;
  text-shadow: 0 0 8px rgba(14, 252, 255, 0.6);
}

.table-header .table-row {
  background: transparent;
}

.table-row:hover {
  background: rgba(102, 204, 255, 0.1) !important;
  box-shadow: inset 0 0 20px rgba(102, 204, 255, 0.12);
}

/* 表格网格布局 */
.table-grid {
  display: grid;
  grid-template-columns: 1.2fr 1fr 1fr 1.2fr;
  gap: v-bind('containerHeight < 400 ? "0.5rem" : "1rem"');
  align-items: center;
  width: 100%;
  transition: gap 0.3s ease;
}

.col-factory,
.col-workshop,
.col-pool,
.col-species {
  text-align: center;
  justify-self: center;
}

.col-factory {
  white-space: wrap;
}

/* 发光效果 */
.table-header div {
  text-shadow: 0 0 12px rgba(102, 204, 255, 0.9);
}

/* 数字发光 */
.text-#e0f836 {
  text-shadow: 0 0 8px rgba(224, 248, 54, 0.6);
}

/* 品种发光 */
.text-#66ccff {
  text-shadow: 0 0 8px rgba(102, 204, 255, 0.6);
}

/* 表格内容区域 */
.table-body {
  position: relative;
}

.table-content {
  transition: opacity 0.3s ease;
}

/* 页面切换动画 */
.table-content.page-transition {
  opacity: 0;
}
</style>
